package com.noovo.comport.server;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class ComProvider extends ContentProvider {
	private static ComSQLiteOpenHelper dbHelper;
	private ContentResolver resolver = null;

	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		return null;
	}

	@Override
	public boolean onCreate() {
		resolver = getContext().getContentResolver();
		dbHelper = new ComSQLiteOpenHelper(getContext());
		return true;
	}

	@Override
	public void shutdown() {
		super.shutdown();
		dbHelper.close();
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection_in, String[] selectionArgs_in,
			String sortOrder) {
		int port = Integer.parseInt(uri.getPathSegments().get(2));
		switch (ComInfo.uriMatcher.match(uri)) {
		case ComInfo.TYPE_PORT_IN_SET:
		case ComInfo.TYPE_PORT_IN_SEND:
			Cursor cursorSet = dbHelper.querySet(port, projection);
			cursorSet.setNotificationUri(resolver, uri);
			return cursorSet;
		case ComInfo.TYPE_PORT_OUT_RECEIVE:
			Cursor cursorReceive = dbHelper.queryReceive(port, projection);
			cursorReceive.setNotificationUri(resolver, uri);
			return cursorReceive;
		default:
			throw new IllegalArgumentException("Error Uri: " + uri);
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection_in, String[] selectionArgs_in) {
		int port = Integer.parseInt(uri.getPathSegments().get(2));
		values.put(ComInfo.DB_ITEM_PORT, port);
		switch (ComInfo.uriMatcher.match(uri)) {
		case ComInfo.TYPE_PORT_IN_SET:
		case ComInfo.TYPE_PORT_IN_SEND:
			dbHelper.updateSet(port, values);
			break;
		case ComInfo.TYPE_PORT_OUT_RECEIVE:
			dbHelper.updateReceive(port, values);
			break;
		default:
			throw new IllegalArgumentException("Error Uri: " + uri);
		}
		resolver.notifyChange(uri, null);
		return 1;
	}
}
